<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss"
                             valueFormat="YYYY-MM-DD HH:mm:ss"/>
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss"
                             valueFormat="YYYY-MM-DD HH:mm:ss"/>
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button @click="downloadFile">下载</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        title="心跳速率"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="heartRateChart"
          style="height: 362px;"
          :option="heartRateChartOption"/>
      </a-card>

      <a-card
        :bordered="false"
        title="呼吸速率"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="respirationRateChart"
          style="height: 362px;"
          :option="respirationRateChartOption"/>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="chdId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openDetail(record)">详情</a>
                <a-divider type="vertical"/>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- 编辑弹窗 -->
    <CattleManagerCattlehealthdataHeartbeatDataDetail v-if="showDetail" v-model:visible="showDetail" :data="current"/>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import {CattleHeartbeatDataApi} from "@/api/property/cattlemanager/CattleHeartbeatDataApi";
import CattleManagerCattlehealthdataHeartbeatDataDetail from './health-heartbeat-data-detail.vue'
import moment from 'moment'
import { message } from 'ant-design-vue';
import {SysDatadownLogApi} from "@/api/system/operation/SysDatadownLogApi";

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);

provide(THEME_KEY, ChartTheme);
export default {
  name: 'CattleManagerCattlehealthdataHeartbeatData',
  components: {
    CattleManagerCattlehealthdataHeartbeatDataDetail,
    VChart
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getHeartData();
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '时间',
          dataIndex: 'createTime'
        },
        {
          title: '呼吸速率(次/min)',
          dataIndex: 'respirationRate'
        },
        {
          title: '心跳速率(次/min)',
          dataIndex: 'heartRate'
        },
        {
          title: '速率状态',
          dataIndex: 'rateState',
          customRender: function (row) {
            if (row.text == 0) {
              return "无目标";
            } else if (row.text == 1) {
              return "信号微弱";
            } else if (row.text == 2) {
              return "呼吸正常";
            } else if (row.text == 3) {
              return "目标异常移动";
            }
          }
        },
        {
          title: '热成像图',
          dataIndex: 'thermalImagingUrl',
          customRender: function (row) {
            if (row.text != undefined && row.text != '') {
              return '详情查看';
            } else {
              return '无';
            }
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {
        "cattleId": this.data.cattleId
      },
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showDetail: false,
      heartData : [],
    }
  },
  computed: {
    //心跳速率
    heartRateChartOption(){
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['心跳速率'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.heartData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '心跳速率',
            type: 'line',
            showSymbol: false,
            data: this.heartData.map(d => d.heartRate)
          },
        ]
      }
    },
    //呼吸速率
    respirationRateChartOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['呼吸速率'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.heartData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '呼吸速率',
            type: 'line',
            showSymbol: false,
            data: this.heartData.map(d => d.respirationRate)
          },
        ]
      }
    },
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({page: 1});
      this.getHeartData();
    }
    ,

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.cattleId = this.data.cattleId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    }
    ,

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    async remove(row) {
      const result = await CattleHeartbeatDataApi.delete({chdId: row.chdId});
      message.success(result.message);
      this.reload();
    },

    getHeartData() {
      let params = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        rateStates : "1,2,3",
        orderBy : "create_time",
        sortBy : "asc"
      };

      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
      }

      CattleHeartbeatDataApi.list(params).then(list => {
        let _heartData = [];
        if (list && list.length > 0) {
          let split = 0;
          if (list.length > 120 && list.length < 180) {
            split = 9;
          } else if (list.length > 180 && list.length < 300) {
            split = 15;
          } else if (list.length > 300) {
            split = 35;
          }
          let i = 0;
          list.forEach(function (item) {
            let formatItem = {
              time: item.createTime.substr(0, 16),
              respirationRate: item.respirationRate,
              heartRate: item.heartRate
            };
            i++;
            if (split == 0) {
              _heartData.push(formatItem);
            } else if (split > 0 && i % split == 0) {
              _heartData.push(formatItem);
            }
          });
        } else {
          _heartData.push({
            time: moment().subtract(20, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
          _heartData.push({
            time: moment().subtract(10, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
          _heartData.push({
            time: moment().subtract(5, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
        }
        this.heartData = _heartData;
      });
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({page, limit, where, orders}) {
      return CattleHeartbeatDataApi.findPage({...where, ...orders, pageNo: page, pageSize: limit});
    },
    downloadFile () {
      if (this.where.searchBeginTime && this.where.searchEndTime) {
        let fromParam = {
          "searchBeginTime" : this.where.searchBeginTime,
          "searchEndTime" : this.where.searchEndTime,
          "cattleId" : this.data.cattleId + "",
        };
        let from = {
          "downName" : "奶牛id为"+this.data.cattleId+"的呼吸心跳数据下载",
          "downScene" : 6,
          "downCondition" : JSON.stringify(fromParam)
        };

        let result = SysDatadownLogApi.add(from);
        result
          .then(result1 => {
            message.success("添加下载任务成功，请移步到【数据下载】->【导出记录】查看")
          })
          .catch(() => {
          });
      } else {
        message.warn("请选择时间条件");
      }
    },
    activated() {
      ['heartRateChart', 'respirationRateChart'].forEach((name) => {
        this.$refs[name].resize();
      });
    }
  }
};
</script>
